<template>
  <div v-loading="queueLoading" class="batchImport" ref="nodeRef" curPageName="batchImport4324234324234234324">
    <layoutContent>
      <template #right>
        <!-- 搜索模块儿 -->
        <div>
          <serachBar
            custom_class="myclass"
            :close-enter="true"
            :close-advanced="true"
            :search_val="search_val"
            @searchEvent="searchFn"
          >
            <template #header>
              <el-autocomplete
                v-model="searchValue"
                value-key="label"
                style="margin-right: 10px; width: 200px"
                clearable
                :placeholder="$t('goods_important_index.operator')"
                :trigger-on-focus="false"
                :fetch-suggestions="querySearch"
                @select="value => (tablePayload.params!.created_by = value.value)"
                @change="value => !value && (tablePayload.params!.created_by = undefined)"
              />
              <el-date-picker
                v-model="searchDate"
                class="custom-date-picker"
                type="daterange"
                :start-placeholder="$t('goods_important_index.begin_date')"
                :end-placeholder="$t('goods_important_index.end_date')"
                :range-separator="$t('merak.rangto')"
                :format="format"
                :value-format="format"
                @change="
                  (value: [string, string] | null) => {
                    tablePayload.params!.begin_date = value?.[0];
                    tablePayload.params!.end_date = value?.[1];
                  }
                "
              />
            </template>
            <template #footer>
              <el-button type="primary" @click="handleExpandCard()">{{ $t("goods_important_index.import_profile") }}</el-button>
              <el-dropdown class="myDropDown" @command="handleCommand">
                <el-button type="primary" plain>
                  {{ $t("goods_important_index.download_template") }} <el-icon class="el-icon--right"><arrow-down /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="consumer">{{ $t("goods_attribute.consumer") }}</el-dropdown-item>
                    <el-dropdown-item command="industrial">{{ $t("goods_attribute.industrial") }}</el-dropdown-item>
                    <el-dropdown-item command="food">{{ $t("goods_attribute.food") }}</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </serachBar>
        </div>
        <div class="merak-table-wrapper">
          <MerakXTable
            ref="tableRef"
            v-bind="tablePayload"
            :query-columns="handleQueryColumns"
            :query-data="handleQueryData"
            @tool-click="handleToolClick"
          >
            <template #job_num_slots="{ row }">
              <!-- :style="`color:${row.color}`" -->
              <el-tooltip
                v-if="row.fail_count > 0"
                popper-class="errNumber"
                placement="top"
                :offset="6"
                :content="$t('goods_important_index.click_error')"
              >
                <span style="color: red; cursor: pointer" @click="errNumberHandle(row)">{{ row.fail_count }}</span>
              </el-tooltip>
              <span v-else>{{ row.fail_count }}</span>
            </template>

            <template #download="{ row }">
              <div style="display: flex">
                <el-button
                  type="primary"
                  link
                  :loading="loadingKeys.includes(row.import_id)"
                  :disabled="row.progress !== '100%'"
                  @click="handleDownload(row)"
                >
                  {{ $t("goods_important_index.export_file") }}
                </el-button>
              </div>
            </template>
          </MerakXTable>
        </div>
      </template>
    </layoutContent>

    <!-- 导入商品档案 -->
    <Transition name="fade" mode="out-in">
      <div v-if="visibleCard" v-waterMarker class="import-card">
        <div class="close" @click="handleCloseCard">
          <Close />
        </div>
        <MerakUploadStep
          :path="UploadStepPath.goods"
          :data="{ import_id: visibleCardId }"
          @uploaded="uploadSuccess = true"
          @back="handleCloseCard"
        />
      </div>
    </Transition>

    <!-- 错误提示框start -->
    <el-dialog modal-class="err-modal" v-model="errDialogVisible" width="500" @close="polling">
      <div class="modalContent">
        <div>
          {{ $t("goods_important_index.import_error") }}
          <span class="errModalNum">{{ errRow.fail_count }}</span>
          {{ $t("goods_important_index.import_error_text") }}
        </div>
        <div>
          {{ $t("goods_important_index.method_one") }}
          <span class="successTip" @click="handleDownload(errRow, true)">{{ $t("goods_important_index.method_one_text") }}</span>
          {{ $t("goods_important_index.method_one_edit") }}
          <span class="successTip" @click="handleExpandCard(errRow.import_id)">{{
            $t("goods_important_index.method_one_again")
          }}</span>
        </div>
        <div>
          {{ $t("goods_important_index.method_two") }}
          <span class="successTip" @click="onlineEditHandale">{{ $t("goods_important_index.method_two_text") }}</span>
        </div>
      </div>
    </el-dialog>
    <!-- 错误提示框start -->
  </div>
</template>
<script setup lang="ts" name="batchImport">
import layoutContent from "@/components/LayoutComponents/index.vue";
import { ref, reactive, computed, getCurrentInstance, onMounted } from "vue";
import serachBar from "@/components/SearchBar/index";
import { useRouter } from "vue-router";
import MerakXTable, { MerakXTableInstance, MerakXTableProps, MerakXTableQuery } from "@/components/MerakXTable";
import { Path, getTableColumns, getTableData } from "@/api/modules/table";
import useLoading from "@/hooks/useLoading";

import useDateFormat from "@/hooks/useDateFormat";

import { ElMessage, ElLoading, ElButton, ElAutocomplete, ElDatePicker, ElDialog, ElTooltip } from "element-plus";
import { Search, Close } from "@element-plus/icons-vue";

import MerakUploadStep from "@/components/MerakUploadStep";

import {
  moreConfirm,
  confirmWarningMsg,
  successMsg,
  warnMsg,
  failMsg,
  confirmSuccessMsg,
  delConfimMsg
} from "@/utils/messageUtils";
import {
  getOfficeLocationListApi,
  saveOfficeLocationApi,
  delOfficeLocationApi,
  getOfficeLocationAllApi,
  mergeOfficeApi
} from "@/api/modules/personalManagementApi/officeLocation";

import { ResultEnum } from "@/enums/httpEnum";
import { exportDataByTable, exportDataByError } from "@/api/modules/goodsArchive/batchImport/import";
import { UploadStepPath, downloadFile } from "@/api/modules/upload";
import { UserAuthType, OptionType, getUserAuth, getUserOptions } from "@/api/modules/user";

const { proxy } = getCurrentInstance() ?? {};

const router = useRouter();

// 使用队列 loading 管理初始化页面加载状态
const { queueLoading, queueId } = useLoading();

const { format } = useDateFormat();

const handleCommand = (command: string) => {
  const map = {
    consumer: "sale", // 日用品
    industrial: "mro", // 工业品
    food: "food" // 食品
  };
  router.push({
    name: "goodsTemplateDownload",
    query: { type: map[command], name: proxy?.$t(`goods_attribute.${command}`) }
  });
};

//#region 错误提示条数
//错误数字提示
const errDialogVisible = ref(false);
const errRow = ref<Record<string, any>>({});
const errNumberHandle = (rows: Record<string, any>) => {
  if (rows.fail_count == 0) {
    return;
  }
  // 关闭轮询
  if (!!timer.value) {
    clearInterval(timer.value);
  }
  console.log(rows);
  errRow.value = rows;
  errDialogVisible.value = true;
};

//在线修改
const openHrefUrl = router.resolve({
  //使用resolve
  name: "goodsOnline", //这里是跳转页面的name
  path: `/goods/important/onlineEdit` //这里是跳转页面的path地址
});
const onlineEditHandale = () => {
  // window.open(openHrefUrl.href, '_blank')
  errDialogVisible.value = false;

  window.open(openHrefUrl.href + `?import_id=${errRow.value.import_id}`, "", "width=1360,height=768");
};

//#endregion

const nodeRef = ref<HTMLDivElement>();

//#region 列表
const tableRef = ref<MerakXTableInstance>();

// 轮询变量
const timer = ref<NodeJS.Timeout>();

// 是否展示导入弹窗
const visibleCard = ref(false);
// 导入弹窗ID
const visibleCardId = ref<string | number>();

// 弹窗是否成功上传
const uploadSuccess = ref(false);

// 搜索操作人
const searchValue = ref<string>();

// 搜索时间区间
const searchDate = ref<[string, string]>();

// 导出加载key
const loadingKeys = ref<Array<string | number>>([]);

// 页面配置数据
const state = reactive<{
  key_words: string;
  userOptions: OptionType[];
}>({
  key_words: "",
  userOptions: []
});

// 动态计算表格的外部筛选数据
// const params = computed(() => ({ key_words: state.key_words }));
// const columnTypeNew = computed(() => state.columnType);
// 表格配置属性
const tablePayload = reactive<MerakXTableProps>({
  loading: false,
  // 列设置存储的数据对照值
  columnsByStore: [],
  // 表格行数据的唯一 key, 跟后端同步
  rowKey: "org_id",
  // 初始化的外部筛选数据
  params: {},
  // 展示选中列及操作列, 可通过传入对象形式扩展特殊列的渲染插槽, 例如
  // columnType: columnTypeNew,
  enabledExport: false, //导出
  // columnType: ['selection',"multiple", "handle"],
  columnType: [{ type: "handle", slot: "download", width: 200 }],
  toolbar: ["refresh"]
  // 批量操作选项
  // batches: [{ type: "delete", text: "批量删除", color: "red" }]
  // 操作列选项
  // handles: [{ type: "delete", text: "删除", color: "red" }]
});

//获取数据

// 权限数组
const authArr = ref<UserAuthType>({});
//查询
let search_val = ref("");
const searchFn = e => {
  state.key_words = e.search;
};
// const getLocationFun = e => {
//   console.log(e, "===");
//   // state.country=e;
// };

// 权限判定表格操作列
// const columnType = computed<MerakXTableProps["columnType"]>(() =>
//   !!authArr.value?.download?.show ? [{ type: "handle", slot: "download", width: 200 }] : []
// );

// 自动补全操作人
const querySearch = (queryString: string, callback: Function) => {
  const results = !!queryString
    ? state.userOptions.filter(option => option.label.toLowerCase().includes(queryString.toLowerCase()))
    : [];
  callback(results);
};

// 导出文件
const handleDownload = async (row: Record<string, any>, err: boolean = false) => {
  errDialogVisible.value = false;
  const animate = requestAnimationFrame(() => {
    // 关闭轮询
    if (!!timer.value) {
      clearInterval(timer.value);
    }
    cancelAnimationFrame(animate);
  });
  if (err) {
    // 导出错误结果文件
    const loadingInstance = ElLoading.service({ target: nodeRef.value, text: "正在下载错误数据,请稍后..." });
    await exportDataByError(row.import_id).then(({ code, data, message }) => {
      if (code == ResultEnum.SUCCESS) {
        const link = document.createElement("a");
        link.href = data.url;
        link.download = data.name ?? Date.now().toString();
        link.target = "_blank";
        link.click();
        // await downloadFile(data.url, data.name).then(status => {
        //   if (!status) {
        //     ElMessage.error(`${data.name} ${proxy?.$t("下载失败")}`);
        //   }
        // });
      } else {
        const msg = typeof message === "string" ? message : Object.values(message)?.[0];
        ElMessage.error(msg);
      }
    });
    loadingInstance.close();
  } else {
    // 操作列导出文件
    loadingKeys.value.push(row.import_id);
    await exportDataByTable(row.import_id).then(({ code, data }) => {
      if (code == ResultEnum.SUCCESS) {
        const link = document.createElement("a");
        link.href = data.url;
        link.download = data.name ?? Date.now().toString();
        link.target = "_blank";
        link.click();
        // await downloadFile(data.url, data.name).then(status => {
        //   if (!status) {
        //     ElMessage.error(`${data.name} ${proxy?.$t("下载失败")}`);
        //   }
        // });
      }
    });
    const index = loadingKeys.value.findIndex(key => key === row.import_id);
    loadingKeys.value.splice(index, 1);
  }
  // 开启轮询
  polling();
};

// 展开上传弹窗
const handleExpandCard = (id?: string | number) => {
  // 关闭轮询
  if (!!timer.value) {
    clearInterval(timer.value);
  }
  errDialogVisible.value = false;
  visibleCardId.value = id;
  visibleCard.value = true;
};

// 关闭上传弹窗
const handleCloseCard = () => {
  if (uploadSuccess.value) {
    tableRef.value?.reloadData();
  } else {
    // 开启轮询
    polling();
  }
  uploadSuccess.value = false;
  visibleCard.value = false;
};

const handleToolClick: MerakXTableInstance["onTool-click"] = type => {
  if (type === "refresh") {
    tablePayload.loading = true;
  }
};

//列表内容展示区
const handleQueryData: MerakXTableProps["queryData"] = async ({ page, sorts, filters, from }) => {
  const params: Record<string, any> = {};
  if (!!page) {
    Object.assign(params, { ...page }, from);
  }
  if (!!timer.value) {
    // 清除轮询
    clearInterval(timer.value);
  }
  return getTableData(Path.goodsImport, params, queueId.value).then(({ code, data }) => {
    tablePayload.loading = false;
    if (code == ResultEnum.SUCCESS) {
      // 重启轮询
      if (!visibleCard.value && !errDialogVisible.value) {
        polling();
      }
      return data.table_data;
    }
  });
};

// 获取表头数据
const handleQueryColumns: MerakXTableInstance["queryColumns"] = async () => {
  // 初始化接口需要传入队列 loading 暴露的 id
  return getTableColumns(Path.goodsImport, queueId.value).then(({ code, data }) => {
    if (code == ResultEnum.SUCCESS) {
      // 克隆表头数据作为列设置的对照数据
      tablePayload.columnsByStore = JSON.parse(JSON.stringify(data.columns));
      for (let index = 0; index < data.columns.length; index++) {
        const element = data.columns[index];
        if (element.field == "fail_count") {
          element["slots"] = { default: "job_num_slots" };
        }
      }
      return {
        ...data
      };
    }
  });
};
//#endregion

// 轮询列表
const polling = () => {
  const delay = 5;
  timer.value = setInterval(() => {
    tableRef.value?.reloadData();
  }, delay * 1000);
};

onMounted(() => {
  polling();
  getUserAuth("batchImport", queueId.value).then(({ code, data }) => {
    if (code == ResultEnum.SUCCESS) {
      authArr.value = data;
    }
  });
  getUserOptions().then(({ code, data }) => {
    if (code == ResultEnum.SUCCESS) {
      state.userOptions = data;
    }
  });
});
</script>

<style scoped lang="scss">
@import "./index.scss";

:deep(.custom-date-picker) {
  width: 300px;
  .el-range-separator {
    margin-top: -3px;
    font-size: var(--merak-text-size);
  }
}

.batchImport {
  position: relative;
}

.import-card {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  padding: var(--merak-padding);
  background-color: var(--bg-color);
  border-radius: var(--merak-rounded);
  z-index: 2000;
  .close {
    margin-bottom: var(--merak-padding);
    text-align: right;
    cursor: pointer;
    & > svg {
      width: 1.2em;
      height: 1.2em;
    }
  }
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>

<style lang="scss">
.dark .errNumber.el-popper {
  --merak-tooltip-color: rgba(146, 146, 148, 1);
  --merak-tooltip-text-color: #000;
  --meark-tooltip-shadow-color: transparent;
  --meark-tooltip-opacity: 0.9;
}
.errNumber.el-popper {
  --merak-tooltip-color: #fff;
  --merak-tooltip-text-color: #646567;
  --meark-tooltip-shadow-color: rgba(0, 23, 40, 0.06);
  --meark-tooltip-opacity: 1;
  line-height: 18px;
  color: var(--merak-tooltip-text-color) !important;
  font-size: 12px;
  background-color: var(--merak-tooltip-color) !important;
  box-shadow: 0px 0px 8px 4px var(--meark-tooltip-shadow-color);
  border: none;
  opacity: var(--meark-tooltip-opacity);
  backdrop-filter: blur(0px);
  .el-popper__arrow {
    width: 0;
    height: 0;
    left: 5px !important;
    bottom: 5px;
    &::before {
      border: 5px solid transparent !important;
      border-left-color: var(--merak-tooltip-color) !important;
      border-bottom-color: var(--merak-tooltip-color) !important;
      background-color: transparent;
      box-shadow:
        0px 2px 0px 0px var(--meark-tooltip-shadow-color),
        0px 0px 0px 0px var(--meark-tooltip-shadow-color);
      transform: rotate(-45deg);
    }
  }
}
</style>
